//
//  ZClubEditVC.m
//  WeClubs
//
//  Created by Zed Link on 28/4/2017.
//  Copyright © 2017 Zed. All rights reserved.
//

#import "ZClubEditVC.h"
#import "ZEditVC.h"
#import "ZClubDepartmentVC.h"
#import "ZClubPositionVC.h"
#import "ZMemberManagerVC.h"
#import <UIImageView+WebCache.h>

@interface ZClubEditVC () <UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate> {
    MBProgressHUD *_hud;
    BOOL _uploadSuccess;
    NSString *_logoImageName;
}

@property (weak, nonatomic) IBOutlet UIImageView *logoImgView;
@property (weak, nonatomic) IBOutlet UILabel *sloganLabel;
@property (weak, nonatomic) IBOutlet UILabel *introductLabel;
@property (weak, nonatomic) IBOutlet UILabel *architecturalLabel;
@property (weak, nonatomic) IBOutlet UILabel *positoinLabel;

//资料完善度View
@property (weak, nonatomic) IBOutlet UIView *progressView;
//资料完善度Label
@property (weak, nonatomic) IBOutlet UILabel *infoLabel;



/** 组织口号 */
@property (copy, nonatomic) NSString *slogan;
/** 组织简介 */
@property (copy, nonatomic) NSString *introduct;

@end

@implementation ZClubEditVC

+ (instancetype)zNew
{
    return [self zStoryboardInstanceWithStoryboardName:@"ClubEdit"];;
}

#pragma mark - About Navigation

- (void)zConfigNavigation
{
    [super zConfigNavigation];
    
    [self zAddBackItemWithGesture:YES];
    self.navigationItem.title = @"组织编辑";
}

- (void)createClubAction
{
    
}

#pragma mark - View Life Cycle

- (void)zLoadSubview
{
    [super zLoadSubview];
    
    [self.logoImgView zCornerDeal:34];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _uploadSuccess = NO;

    [self setupNotification];
}


- (void)setupNotification{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(uploadAction:) name:kDidUploadImageNotification object:nil];


//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateContent) name:kUpDataOrganizationNotification object:nil];
    

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self updateContent];
}

- (void)uploadAction:(NSNotification *)notification
{
    [_hud hideAnimated:YES];
    
    NSDictionary *userInfo = notification.userInfo;
    BOOL result = [userInfo[ZNetManagerDidUploadImageNotificationStateKey] boolValue];
    
    if (result == YES) {
        UIImage *image = userInfo[ZNetManagerDidUploadImageNotificationImageKey];
        [self.logoImgView setImage:image];
    
        _logoImageName = userInfo[ZNetManagerDidUploadImageNotificationURLKey];
        [MBProgressHUD zAlertToastMessage:@"Logo上传成功"];
    } else {
        [MBProgressHUD zAlertToastMessage:@"Logo上传失败"];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Private Method

- (void)updateContent
{
    
    if (self.model.avatar_url != nil) {
        NSURL *url = [NSURL URLWithString:self.model.avatar_url];
        [self.logoImgView sd_setImageWithURL:url];
    }    
    [self setupTopUI];
    
    [self setSlogan:self.model.slogan];
    [self setIntroduct:self.model.introduction];
    
    BOOL hasDepartment = [self.model.departments isEqualToString:@""] == NO;
 
    self.architecturalLabel.hidden = hasDepartment;
    
    BOOL hasPosition = [self.model.jobs isEqualToString:@""] == NO;
    self.positoinLabel.hidden = hasPosition;

}

- (void)setupTopUI{
    CGFloat w =self.model.finishCount/100*Z_SCREEN_WIDTH;
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(w);
        make.height.mas_equalTo(32);
    }];
    self.infoLabel.text = [NSString stringWithFormat:@"资源完善度%0.f%%",self.model.finishCount];
    self.infoLabel.textColor = [UIColor whiteColor];
    __weak typeof(self) weakSelf = self;
    [self.infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(weakSelf.progressView.mas_centerY);
        make.right.mas_equalTo(-15);
    }];
    
}

-(void)loadImagePicker{

    UIActionSheet *actionSheet =[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消"  destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"选择照片", nil];
    
    [actionSheet showInView:self.view];

    
}


#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    
    if(buttonIndex == 0){
        
        [self chooseImaage:UIImagePickerControllerSourceTypeCamera]; //拍照
        
    }else if(buttonIndex == 1){
        
        [self chooseImaage:UIImagePickerControllerSourceTypePhotoLibrary]; //选择照片
        
    }


}

-(void)chooseImaage:(UIImagePickerControllerSourceType)soureType{
    
    UIImagePickerController *pickerVc =[[UIImagePickerController alloc]init];
    pickerVc.delegate = self;
    pickerVc.sourceType = soureType;
    pickerVc.allowsEditing = YES;
    _uploadSuccess = YES;
    [self presentViewController:pickerVc animated:YES completion:nil];
    
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.1f;
    }
    return 12.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger index = indexPath.section * 100 + indexPath.row;
    switch (index) {
        case 0 + 0:     // 组织Logo
        {
            [self loadImagePicker];

        }
            break;
        case 100 + 0:     // 组织口号
        {
            ZEditVC *editVC = [ZEditVC zNew];
            [editVC setTitle:@"组织口号" andPlaceHolder:@"请输入组织口号"];
            [editVC setInputText:self.slogan];
            
            editVC.didSubmitText = ^(NSString *text) {
                _hud = [MBProgressHUD zAlertProgress:@"正在修改组织口号"];
                #warning Done
                
                NSDictionary *dataPara = @{
                                           @"user_id" : @([ZUserInfo sharedInstance].userId),
                                           @"token" : [ZUserInfo sharedInstance].token,
                                           @"club_id" : @(self.model.clubId),
                                           @"slogan" : text,
                                           };
                
            [HTTPRequest POST:kEdit_club_sloganUrl parameter:dataPara success:^(id resposeObject) {
               
                self.model.slogan = text;
                  [self setSlogan:text];
                [_hud hideAnimated:YES];
            } failure:^(NSError *error) {
               
                [_hud hideAnimated:YES];
            [MBProgressHUD zAlertToastMessage:@"组织口号修改失败"];

            }];
            };
            
            [self.navigationController pushViewController:editVC animated:YES];
        }
            break;
        case 100 + 1:     // 组织简介
        {
            ZEditVC *editVC = [ZEditVC zNew];
            [editVC setTitle:@"组织简介" andPlaceHolder:@"请输入组织简介"];
            [editVC setInputText:self.introduct];
            
            editVC.didSubmitText = ^(NSString *text) {
                _hud = [MBProgressHUD zAlertProgress:@"正在修改组织口号"];

                #warning Done
                NSDictionary *dataPara = @{
                                           @"user_id" : @([ZUserInfo sharedInstance].userId),
                                           @"token" : [ZUserInfo sharedInstance].token,
                                           @"club_id" :@(self.model.clubId),
                                           @"introduction" :text
                                           };
                
                  [HTTPRequest POST:kEdit_club_introductionUrl parameter:dataPara success:^(id resposeObject) {
                     
                      self.model.introduction = text;
                       [self setIntroduct:text];
                       [_hud hideAnimated:YES];
                  } failure:^(NSError *error) {
                  [_hud hideAnimated:YES];
                 [MBProgressHUD zAlertToastMessage:@"组织简介修改失败"];
                  }];

            };
            
            [self.navigationController pushViewController:editVC animated:YES];
        }
            break;
        case 200 + 0:     // 组织架构
        {
            ZClubDepartmentVC *vc = [ZClubDepartmentVC zNew];
            vc.type = ZClubDepartmentTypeModify;
            vc.clubId = @(self.model.clubId);
            
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 200 + 1:     // 职位制定
        {
            ZClubPositionVC *vc = [ZClubPositionVC zNew];
            vc.clubId = @(self.model.clubId);
            
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 300 + 0:     // 成员管理
        {
            ZMemberManagerVC *vc = [ZMemberManagerVC zNew];
            vc.clubId = self.model.clubId;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image =[info objectForKey:UIImagePickerControllerOriginalImage];
    
    _logoImgView.image = image;
    
    
    
    [self uploadImage:image];
    
}

- (void)uploadImage:(UIImage *)image{


    
    [HTTPRequest uploadImage:image named:nil success:^(id resposeObject) {
   
       _hud = [MBProgressHUD zAlertProgress:@"正在上传组织Logo"];
            [self.logoImgView setImage:image];
        
        _logoImageName  = resposeObject;
        ZLog(@"________%@",_logoImageName);//
    } failure:^(NSError *error) {
       
    }];
    

}
#pragma mark - Getter & Setter

- (void)setSlogan:(NSString *)slogan
{
    _slogan = slogan;
    
    if (_slogan == nil || [_slogan isEqualToString:@""]) {
        self.sloganLabel.text = @"未设置";
        self.sloganLabel.textAlignment = NSTextAlignmentRight;
        self.sloganLabel.textColor = PLACE_HOLDER_COLOR;
    } else {
        self.sloganLabel.text = slogan;
        self.sloganLabel.textAlignment = NSTextAlignmentLeft;
        self.sloganLabel.textColor = FONT_MAIN_COLOR;
    }
}

- (void)setIntroduct:(NSString *)introduct
{
    _introduct = introduct;
    
    if (_introduct == nil || [_introduct isEqualToString:@""]) {
        self.introductLabel.text = @"未设置";
        self.introductLabel.textAlignment = NSTextAlignmentRight;
        self.introductLabel.textColor = PLACE_HOLDER_COLOR;
    } else {
        self.introductLabel.text = introduct;
        self.introductLabel.textAlignment = NSTextAlignmentLeft;
        self.introductLabel.textColor = FONT_MAIN_COLOR;
    }
}

- (void)setModel:(ZOwnerClubModel *)model
{
    _model = model;

    [self updateContent];
}

@end
